<!--这是上传视频组件-->
<template>
	<div style="padding-bottom: 30px;">
		<div class="addBox">
			<div style="margin: 0 20px;">
				<p style="line-height: 36px;">已上传列表：</p>
				<table>
					<tr>
            <th>系列名称</th>
						<th>编号</th>
            <th>章节名称</th>
            <th>视频ID</th>
            <th>视频唯一码</th>
            <th>乐视状态</th>
            <th>排序</th>
						<th>操作</th>
					</tr>
            <tr v-for="(item,index) in data.vedioList" :key="index">
                <td>{{item.name}}</td>
                <td>{{item.courseDetailId}}</td>
                <td>{{item.videoName}}</td>
                <td>{{item.pfVideoId}}</td>
                <td>{{item.letvUnique}}</td>
                <td>{{item.state}}</td>
                <td>{{item.sort}}</td>
                <td>
                    <b @click="deleteVideo(item.courseDetailId, item.pfVideoId)">删除</b>
                    <b @click="linkToEdit(item.courseDetailId,index)">编辑</b>
                </td>
            </tr>
		</table>
        <code>
          <svg-icon icon-class="message" style="margin-right:10px;color:red;font-size:20px;"></svg-icon>
          提示：
          视频格式只支持MP4格式
        </code>
        <el-upload
          class="upload-demo"
          ref="upload"
          action="https://upload.qiniup.com/"
          :on-change="onChange"
          :before-upload="beforeUpload"
          :show-file-list="false"
          :data="formData"
          :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary"  id="chooseFile">选取文件</el-button>
          <el-button style="margin-left: 10px;" v-loading="btnLoading" size="small"  type="success" @click="submitUpload">上传到服务器</el-button>
          <!-- <el-button size="small" type="danger" @click="cancelUpload">取消上传</el-button> -->
        </el-upload>
			</div>
			<div style="margin: 0 20px;">
				<p style="line-height: 36px;">上传进度：</p>
				<table>
					<tr>
						<th>视频名称</th>
						<th>上传进度</th>
            <th>上传速度</th>
						<th>上传状态</th>
					</tr>
					<tr v-if="uploadShow">
						<td>{{ fileName }}</td>
						<td id="videoProgress"></td>
            <td id="videoSpeed"></td>
						<td id="videoStatus"></td>
					</tr>
				</table>
      </div>
    </div>
    <editUploadVideo v-show="isShowEdit" @hideEdit="hideEdit" :id="data.courseDetailId" @getData="getUpdateData"></editUploadVideo>
  </div>
</template>
<script>
  import editUploadVideo from './editUploadVideoLeShi'
  import { initLetV } from '@/api/courseDetail'
  import { getCourseVedio, setCourseVedio } from '@/api/courseDetail'
  import $ from 'jquery'
  import { getVideoPlatformType } from '@/api/company'
  const postForm = {
    audioName: null,
    qiniuObject: null
  }

  const uploadList = [] // 储存上传的视频数据

  export default {
    components: {
      editUploadVideo
    },
    data() {
      return {
        postForm,
        uploadList,
        uploadData: {},
        formData: {
          token: null
          // key: null
        },
        fileName: null, // 上传视频的文件名
        speed: null, // 上传速度
        percent: null, // 进度
        status: null,
        listShow: false, // 是否显示上传列表
        uploadShow: false, // 是否显示上传文件的状态
        btnLoading: false,
        courseId: null,
        isShowEdit: false, // 是否显示编辑视频组件
        courseDetailId: null,
        token: null,
        data: {
          courseDetailId: null,
          courseId: null,
          videoName: null,
          pfVideoId: null,
          letvUnique: null,
          videoSrc: null,
          videoUrl: null,
          sort: null,
          opType: null,
          vedioList: null
        }
      }
    },
    created() {
      // 刷新列表
      getCourseVedio(this.$route.params.courseId)
        .then(res => {
          this.token = res['config']['headers']['Authorization'].split(' ')[1]
          this.data.vedioList = res.data.data
        })
        .catch(err => {
          console.log(err)
        })
    },
    methods: {
      hideEdit(msg) {
        this.isShowEdit = msg
      },
      getUpdateData(data) {
        getCourseVedio(this.$route.params.courseId)
          .then(res => {
            this.data.vedioList = res.data.data
          })
          .catch(err => {
            console.log(err)
          })
      },
      linkToEdit(id, index) {
        this.data.courseDetailId = id
        this.isShowEdit = true
      },
      deleteVideo(id, pfVideoId) {
        this.$confirm('确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        // 删除成功
          this.data.courseDetailId = id
          this.data.pfVideoId = pfVideoId
          this.data.opType = 3
          setCourseVedio(this.data).then(res => {
            // 刷新列表
            getCourseVedio(this.$route.params.courseId)
              .then(res => {
                this.data.vedioList = res.data.data
              })
              .catch(err => {
                console.log(err)
              })
          })

          // 删除成功
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      beforeUpload(file) {
        // this.formData.key = 'courses/' + this.courseId + '/' + file.name
        this.percent = '0%'
        this.status = '开始上传'
      },
      onChange(file, filelist) {
        const isMP4 = file.raw.type == 'video/mp4'
        // const maxSize = file.raw.size / 1024 / 1024 < 100
        if (!isMP4) {
          this.$message({
            message: '视频必须为 MP4 格式',
            type: 'warning'
          })
          return false
        }
        this.fileName = file.name
        this.uploadData = file
        $('#videoProgress').html('')
        $('#videoSpeed').html('')
        $('#videoStatus').html('')
        this.uploadShow = true
      },
	  cancelUpload() {
        qcVideo.ugcUploader.cancel({
          cos: this.cos,
          taskId: this.taskId
        })
        this.btnLoading = false
      },
      submitUpload() {
        if (this.fileName == null) {
          this.$message({
            message: '请选择要上传的视频文件',
            type: 'warning'
          })
          return false
        }

        getVideoPlatformType().then(res => {
          if (res.data.data[0].videoPlatformType == 1) {
            this.$confirm('已切换到腾讯视频上传，请退出当前页面，重新点击上传视频！', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$router.push({ path: `/courses/${this.courseId}/uploadVideo` })
            }).catch(() => {
              this.$router.push({ path: `/courses/${this.courseId}/uploadVideo` })
            })
            return
          }

          this.btnLoading = true
          this.$nextTick(function() {
            var elm = document.querySelector('.el-loading-mask')
              if (elm != null) {
              document.querySelector('.el-loading-mask').style.display = 'block';
            }
          })
          this.$refs.upload.submit()
          $('#chooseFile').next().attr('disabled', true)
          $('#chooseFile').attr('class', 'el-button el-button--primary el-button--small is-disabled')
          window.uploadFunction({
            file: this.uploadData.raw, // 要上传的文件
            uploadUrl: process.env.BASE_API + '/video/initLetV?token=' + this.token
          }, process.env.BASE_API, this.data, this.$route.params.courseId, this.token)
       })
      },
      close() { // 关闭当前窗口
        console.log(this.$route)
        if ($('#chooseFile').next().attr('disabled')) {
          console.log('zhengzaichuan')
        } else {
          var obj = {
            name: this.$route.name,
            path: this.$router.path,
            title: this.$route.meta.title
          }
          this.$store.dispatch('delVisitedViews', obj).then((views) => {
            const latestView = views.slice(-1)[0]
            console.log(latestView)
            if (latestView) {
              this.$router.push(latestView.path)
            } else {
              this.$router.push('/')
            }
          })
        }
      }
    }
  }
</script>

<style scoped>
	p,h3 {margin:0;padding:0}

	.addBox {
		width: 100%;
		overflow: auto;
		background: #fff;
	}
	table,tr,td,th{
		border: 1px solid #ddd;
		border-collapse: collapse;
		border-spacing: 0;
		text-align: center;
	}
	th{
		background: #f5fafe;
	}
	table{
		font-size: 12px;
		color: #333;
		width: 100%;
		line-height: 36px;
		margin-bottom: 20px;
	}
	b{
    	cursor: pointer;
    	font-weight: 500;
    }
	b:hover{
		color: #0A76A4;
  }
</style>
